package com.centling.smartSealForPhone.activity;

import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.centling.smartSealForPhone.BuildConfig;
import com.centling.smartSealForPhone.R;
import com.centling.smartSealForPhone.bean.BossModeInfo;
import com.centling.smartSealForPhone.bean.DeviceTypeBean;
import com.centling.smartSealForPhone.bean.LoginBean;
import com.centling.smartSealForPhone.constants.GlobalData;
import com.centling.smartSealForPhone.constants.SPConstants;
import com.centling.smartSealForPhone.constants.UrlConstants;
import com.wsdk.service.BluetoothLeService;
import com.centling.smartSealForPhone.utils.BlueToothScanUtil;
import com.centling.smartSealForPhone.utils.ControlUtil;
import com.centling.smartSealForPhone.utils.ImageUtil;
import com.centling.smartSealForPhone.utils.LogUtil;
import com.centling.smartSealForPhone.utils.OkHttpUtil;
import com.centling.smartSealForPhone.utils.ParseBluetoothData;
import com.centling.smartSealForPhone.utils.SPUtil;
import com.centling.smartSealForPhone.utils.ShowDialog;
import com.centling.smartSealForPhone.utils.ShowToast;
import com.centling.smartSealForPhone.view.RoundImgView;
import com.google.gson.Gson;

import java.util.HashMap;
import java.util.Map;

public class BossModeDetailActivity extends TitleBarActivity implements BlueToothScanUtil.StopSearchListener {

    private static final int UNLOCK = 1992;

    private TextView tvStatus;
    private RoundImgView ivAvatar;
    private TextView tvCreatedBy;
    private TextView tvCreatedDate;
    private TextView tvBeginBy;
    private TextView tvEndBy;
    private TextView tvBeginDate;
    private TextView tvEndDate;
    private TextView tvReason;
    private LinearLayout llFail;
    private TextView tvFailReason;
    private TextView tvIsValid;
    private TextView pressBtn;

    private BossModeInfo item;
    private String bossApplyId;
    private DeviceTypeBean deviceTypeBean;

    private BroadcastReceiver bluetoothReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();

            if (BluetoothLeService.ACTION_GATT_SERVICES_DISCOVERED.equals(action)) {
                mProcessDialog.dismiss();
                if (BuildConfig.DEBUG) {
                    ShowToast.shortTime("Boss Mode Connected");
                }
                GlobalData.isConnect = true;
            } else if (BluetoothLeService.ACTION_DATA_AVAILABLE.equals(action)) {
                byte[] data = intent.getByteArrayExtra(BluetoothLeService.EXTRA_DATA);
                if (ParseBluetoothData.isOpenBoss(data)) {
                    Map<String, String> param = new HashMap<>();
                    putJsonEnqueue(UrlConstants.BOSSMODE_BEGIN + bossApplyId + "/begin", param, new OkHttpUtil.NetCallBack() {
                        @Override
                        public void onSucceed(String json) {
                            ShowToast.shortTime("解锁模式开启成功");
                            finish();
                        }

                        @Override
                        public void onFailed(String reason) {
                            ShowToast.shortTime(reason);
                        }
                    });
                } else if (ParseBluetoothData.isWorkMode(data)) {
                    Map<String, String> param = new HashMap<>();
                    putJsonEnqueue(UrlConstants.BOSSMODE_BEGIN + bossApplyId + "/end", param, new OkHttpUtil.NetCallBack() {
                        @Override
                        public void onSucceed(String json) {
                            ShowToast.shortTime("解锁模式关闭成功");

                            finish();
                        }

                        @Override
                        public void onFailed(String reason) {
                            ShowToast.shortTime(reason);
                        }
                    });
                }
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_boss_mode_detail);
        setTitleBarText("解锁模式详情");
        String json = getIntent().getStringExtra("bossModeInfo");
        item = new Gson().fromJson(json, BossModeInfo.class);
        Log.e("item",item.toString());

        LoginBean loginBean = new Gson().fromJson(SPUtil.getString(SPConstants.LOGIN_JSON), LoginBean.class);
        macAddress = loginBean.getEquipRegisterInfo().getBlueToothMac();
        sn = SPUtil.getString(SPConstants.CORE_SN);

        if (TextUtils.isEmpty(macAddress)) {
            ShowToast.shortTime("获取用户绑定设备信息失败");
            finish();
        }

        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(BluetoothLeService.ACTION_GATT_SERVICES_DISCOVERED);
        intentFilter.addAction(BluetoothLeService.ACTION_DATA_AVAILABLE);
        registerReceiver(bluetoothReceiver, intentFilter);

        initView();
        setData();
    }

    public void initView() {
        pressBtn = (TextView) findViewById(R.id.tv_unlock_use);
        tvStatus = (TextView) findViewById(R.id.boss_mode_detail_status);
        ivAvatar = (RoundImgView) findViewById(R.id.boss_mode_detail_avatar);
        tvCreatedBy = (TextView) findViewById(R.id.boss_mode_detail_apply);
        tvCreatedDate = (TextView) findViewById(R.id.boss_mode_detail_date);
        tvBeginBy = (TextView) findViewById(R.id.boss_mode_detail_begin);
        tvEndBy = (TextView) findViewById(R.id.boss_mode_detail_end);
        tvBeginDate = (TextView) findViewById(R.id.boss_mode_detail_begin_date);
        tvEndDate = (TextView) findViewById(R.id.boss_mode_detail_end_date);
        tvReason = (TextView) findViewById(R.id.boss_mode_detail_reason);
        llFail = (LinearLayout) findViewById(R.id.boss_mode_detail_fail);
        tvFailReason = (TextView) findViewById(R.id.boss_mode_detail_fail_reason);
        tvIsValid = (TextView) findViewById(R.id.boss_mode_detail_isValid);
    }

    public void setData() {
        switch (item.getStatus()) {
            case "0":
                tvStatus.setText("外带中");
                break;
            case "1":
                tvStatus.setText("审核通过");
                break;
            case "2":
                tvStatus.setText("审核中");
                break;
            case "3":
                tvStatus.setText("审核失败");
                llFail.setVisibility(View.VISIBLE);
                tvFailReason.setText(item.getAuditFailedReason());
                break;
            case "6":
                tvStatus.setText("已完成");
                break;
            default:
                tvStatus.setText("过期");
                break;
        }
        if ("0".equals(item.getIsValid())) {
            tvIsValid.setText("正常");
        } else {
            tvIsValid.setText("换章失效");
        }
        if ("0".equals(item.getStatus())) {
            pressBtn.setVisibility(View.VISIBLE);
            pressBtn.setText("关闭解锁模式");
            pressBtn.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (!BlueToothScanUtil.isBlueToothOpened()) {
                        Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
                        startActivityForResult(enableBtIntent, UNLOCK);
                        return;
                    }
                    if (GlobalData.isConnect) {
                        if ("0".equals(GlobalData.selfCheckStatus)) {
                            LogUtil.d(GlobalData.isConnect + "");
                            bossApplyId = item.getBossId();
                            sendRequestToCheckIsBossEnd();
                        } else {
                            ShowToast.shortTime("设备异常，请联系管理员! ");
                        }
                    } else {
                        ShowDialog.showSelectDialog(mContext, "重新连接蓝牙", "蓝牙未连接，请先连接蓝牙", "",
                                new View.OnClickListener() {

                                    @Override
                                    public void onClick(View v) {
                                        mProcessDialog.setTitle("正在连接蓝牙").showNormal();
                                        blueToothScanUtil.setMacAddress(macAddress);
                                        blueToothScanUtil.startSearchBlueDevice();
                                        blueToothScanUtil.setStopSearchListener(
                                                BossModeDetailActivity.this);
                                    }
                                });
                    }
                }
            });

        } else if ("1".equals(item.getStatus()) && "1".equals(item.getTimeStatus())) {
            pressBtn.setVisibility(View.VISIBLE);
            pressBtn.setText("开启解锁模式");
            pressBtn.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (!BlueToothScanUtil.isBlueToothOpened()) {
                        Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
                        startActivityForResult(enableBtIntent, UNLOCK);
                        return;
                    }
                    if (GlobalData.isConnect) {
                        if ("0".equals(GlobalData.selfCheckStatus)) {
                            LogUtil.d(GlobalData.isConnect + "");
                            bossApplyId = item.getBossId();
                            sendRequestToCheckIsBoss();
                        } else {
                            ShowToast.shortTime("设备异常，请联系管理员! ");
                        }
                    } else {
                        ShowDialog.showSelectDialog(mContext, "重新连接蓝牙", "蓝牙未连接，请先连接蓝牙", "", new View.OnClickListener() {

                            @Override
                            public void onClick(View v) {
                                mProcessDialog.setTitle("正在连接蓝牙").showNormal();
                                blueToothScanUtil.setMacAddress(macAddress);
                                blueToothScanUtil.startSearchBlueDevice();
                                blueToothScanUtil.setStopSearchListener(BossModeDetailActivity.this);
                            }
                        });
                    }
                }
            });
        }
        ImageUtil.loadAvatarImage(item.getAvatar(), ivAvatar, R.drawable.iv_avatar_default);
        tvCreatedBy.setText(item.getAppllicant());
        tvCreatedDate.setText(item.getStartTimeReal());
        tvBeginBy.setText(item.getStartByName());
        tvEndBy.setText(item.getStopByName());
        tvBeginDate.setText(item.getStartDateReal());
        tvEndDate.setText(item.getStopDateReal());
        tvReason.setText(item.getApplyReason());
    }

    private void sendRequestToCheckIsBossEnd() {
        getEnqueue(UrlConstants.GET_DEVICE_STATE + GlobalData.BOSSMODEEND, new OkHttpUtil.NetCallBack() {
            @Override
            public void onSucceed(String json) {
                deviceTypeBean = new Gson().fromJson(json, DeviceTypeBean.class);
                if (deviceTypeBean.isAllowed()) {
                    new ControlUtil().closeBoss();
                } else {
                    ShowToast.shortTime(deviceTypeBean.getMessage());
                }
            }

            @Override
            public void onFailed(String reason) {
                ShowToast.shortTime(reason);
            }
        });
    }

    private void sendRequestToCheckIsBoss() {
        getEnqueue(UrlConstants.GET_DEVICE_STATE + GlobalData.BOSSMODE, new OkHttpUtil.NetCallBack() {
            @Override
            public void onSucceed(String json) {
                deviceTypeBean = new Gson().fromJson(json, DeviceTypeBean.class);
                if (deviceTypeBean.isAllowed()) {
                    new ControlUtil().openBoss();
                } else {
                    ShowToast.shortTime(deviceTypeBean.getMessage());
                }
            }

            @Override
            public void onFailed(String reason) {
                ShowToast.shortTime(reason);
            }
        });
    }

    @Override
    public void onStopped(boolean timeout) {
        mProcessDialog.dismiss();
        if(timeout) {
            ShowToast.shortTime("连接设备失败");
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == UNLOCK && resultCode == Activity.RESULT_CANCELED) {
            finish();
        }
    }
}
